package com.bike.controller.api;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.bike.cache.UserCache;
import com.bike.controller.BaseController;
import com.bike.entity.HhBusiness;
import com.bike.entity.HhBusinessRecord;
import com.bike.entity.HhBusinessUser;
import com.bike.entity.HhFood;
import com.bike.entity.HhPayRecord;
import com.bike.service.impl.HhBusinessRecordServiceImpl;
import com.bike.service.impl.HhBusinessServiceImpl;
import com.bike.service.impl.HhBusinessUserServiceImpl;
import com.bike.service.impl.HhOrderServiceImpl;
import com.bike.service.impl.HhPayRecordServiceImpl;
import com.bike.util.Constant;
import com.bike.util.Md5Util;
import com.bike.util.PageData;
import com.bike.util.StrUtil;
import com.topit.show.aliapi.SmsUtil;

 
@Controller
@RequestMapping(value="/apiH5")
public class HhApiH5Controller extends BaseController {
	
	@Autowired
	 HhBusinessServiceImpl hhBusinessServiceImpl;
	@Autowired
	HhBusinessRecordServiceImpl hhRecordServiceImpl  ;
	@Autowired
	HhBusinessUserServiceImpl hhBusinessUserServiceImpl  ;
	@Autowired
	HhPayRecordServiceImpl hhPayRecordServiceImpl  ;
	@Autowired
	HhOrderServiceImpl hhOrderServiceImpl  ;
	@Autowired
	private UserCache  usercache;
	/**
	 * 个人中心首页
	 */
	@RequestMapping("index")
	public String index(HttpServletRequest request,Model model){
		PageData pd=PageData.getToPageData(request);
		model.addAttribute("pd",pd);
		return "/h5/personIndex";
	}
	/**
	 * 个人中心
	 */
	@RequestMapping("personMsg")
	public String personMsg(HttpServletRequest request,Model model){
		HhBusinessUser businessUser=(HhBusinessUser) request.getAttribute("businessUser");
		HhBusiness business=hhBusinessServiceImpl.selectByHhBusinessId(businessUser.getBusinessId());
		
		model.addAttribute("business",business);
		model.addAttribute("businessUser",businessUser);
		return "/h5/personMsg";
	}
	/**
	 * 跳到提现页面
	 */
	@RequestMapping("toWithdraw")
	public String toWithdraw(HttpServletRequest request,Model model){
		PageData pd=PageData.getToPageData(request);
		HhBusinessUser businessUser=(HhBusinessUser) request.getAttribute("businessUser");
		HhBusiness business=hhBusinessServiceImpl.selectByHhBusinessId(businessUser.getBusinessId());

		
		
		BigDecimal serviceFee=null;
		BigDecimal trueAccount=business.getBalance();
		
		BigDecimal waitWithdrawMoney=business.getBalance();
		String bank=business.getBank();
		String bankCode=business.getBankCode();
		String bankName=business.getBankName();
		String bankBranch=business.getBankBranch();
		
		if(businessUser.getRole().equals(Constant.employ)){
			waitWithdrawMoney=businessUser.getBalance();
			bank=businessUser.getBank();
			bankCode=businessUser.getBankCode();
			bankName=businessUser.getBankName();
			bankBranch=businessUser.getBankBranch();
		}
		
		if(business.getPayWithdraw()==0){
			serviceFee=waitWithdrawMoney.multiply(new BigDecimal(Constant.WXwithdrawFee)).setScale(2, RoundingMode.HALF_UP);
			if(serviceFee.doubleValue()==0){
				serviceFee=new BigDecimal("0.01");
			}
			trueAccount=waitWithdrawMoney.subtract(serviceFee);
			model.addAttribute("serviceFee",serviceFee.doubleValue());
		}
		trueAccount=trueAccount.subtract(new BigDecimal("2"));//银联转账手续费
		businessUser=hhBusinessUserServiceImpl.selectByHhBusinessUserId(businessUser.getBusinessUserId());
		
		
		model.addAttribute("trueAccount",trueAccount.doubleValue());
		model.addAttribute("business",business);
		model.addAttribute("bank",bank);
		model.addAttribute("waitWithdrawMoney",waitWithdrawMoney);
		model.addAttribute("bankCode",bankCode);
		model.addAttribute("bankName",bankName);
		model.addAttribute("bankBranch",bankBranch);
		model.addAttribute("pd",pd);
		return "/h5/personWithdraw";
	}
	/**
	 * 账户明细
	 */
	@RequestMapping("personRecord")
	public String personRecord(HttpServletRequest request,Model model){
		PageData pd=PageData.getToPageData(request);
		HhBusinessUser businessUser=(HhBusinessUser) request.getAttribute("businessUser");
		if(businessUser.getRole().equals(Constant.employ)){
			
			pd.put("businessUserId", businessUser.getBusinessUserId());
			List<HhPayRecord> HhPayRecord= hhPayRecordServiceImpl.listAll(pd);
			
			model.addAttribute("payRecords",HhPayRecord);
			model.addAttribute("userId",businessUser.getBusinessUserId());
			return "/h5/personEmployRecord";
		}
		
		pd.put("businessId", businessUser.getBusinessId());
		List<HhBusinessRecord> businessRecords= hhRecordServiceImpl.listAll(pd);
		
		model.addAttribute("businessRecords",businessRecords);
		return "/h5/personRecord";
	}
	/**
	 * 意见反馈
	 */
	@RequestMapping("personIdea")
	public String personIdea(HttpServletRequest request,Model model){
		
		return "/h5/personIdea";
	}
	/**
	 * 修改密码页面
	 */
	@RequestMapping("personPwd")
	public String personPwd(HttpServletRequest request,Model model){
		HhBusinessUser businessUser=(HhBusinessUser) request.getAttribute("businessUser");
		
		model.addAttribute("businessUser", businessUser);
		return "/h5/personPwd";
	}
	/**
	 * 统计分析
	 */
	@RequestMapping("count")
	public String count(HttpServletRequest request,Model model){
		HhBusinessUser businessUser=(HhBusinessUser) request.getAttribute("businessUser");
		
		
		
		model.addAttribute("businessUser", businessUser);
		return "/h5/personCount";
	}
	/**
	 * 修改密码
	 * param  businessUserId
	 * param  pwd  旧密码
	 * param  newPwd 新密码
	 */
	@RequestMapping("updatePwdH5")
	public String updatePwdH5(HttpServletRequest request,HhFood food,Model model){
		PageData pd=PageData.getToPageData(request);
		
		HhBusinessUser hhBusinessUser=hhBusinessUserServiceImpl.selectByHhBusinessUserId(pd.getLong("businessUserId"));
		HhBusinessUser businessUser=(HhBusinessUser) request.getAttribute("businessUser");
//		if(hhBusinessUser!=null&&hhBusinessUser.getBusinessId().longValue()==businessUser.getBusinessId()){
			
			if(hhBusinessUser.getPwd().equals(Md5Util.MD5(pd.getString("pwd")))){
				hhBusinessUser.setPwd(Md5Util.MD5(pd.getString("newPwd")));
			}
			int result= hhBusinessUserServiceImpl.saveOrUpdate(pd, hhBusinessUser);
//		}
		return "/h5/personPwd";
	}
	/**
	 *  统计详情
	 * param  businessUserId
	 */
	@RequestMapping("countItem")
	public String countItem(HttpServletRequest request,HhFood food,Model model){
		PageData pd=PageData.getToPageData(request);
		HhBusinessUser businessUser=(HhBusinessUser) request.getAttribute("businessUser");
		
		pd=hhOrderServiceImpl.selectCountInfo(businessUser,pd);
		
		model.addAttribute("pd", pd);
		return "/h5/personCount";
	}
	/**
	 *  添加银行卡
	 * param   bankName 持卡人姓名
	 * param   bankCard  卡号
	 * param   bank  开户行
	 * param   bankBranch  开户分行
	 */
	@RequestMapping("addBank")
	@ResponseBody
	public PageData addBank(HttpServletRequest request,HhFood food,Model model){
		PageData pd=PageData.getToPageData(request);
		HhBusinessUser businessUser=(HhBusinessUser) request.getAttribute("businessUser");
		if(businessUser.getRole().equals(Constant.boss)){
			HhBusiness business=new HhBusiness();
			business.setBusinessId(businessUser.getBusinessId());
			business.setBank(pd.getString("bank"));
			business.setBankBranch(pd.getString("bankBranch"));
			business.setBankCode(pd.getString("bankCard"));
			business.setBankName(pd.getString("bankName"));
			hhBusinessServiceImpl.updateBusiness(pd, business);
		}else{
			HhBusinessUser businessUserRecord=new HhBusinessUser();
			businessUserRecord.setBusinessUserId(businessUser.getBusinessUserId());
			businessUserRecord.setBank(pd.getString("bank"));
			businessUserRecord.setBankBranch(pd.getString("bankBranch"));
			businessUserRecord.setBankCode(pd.getString("bankCard"));
			businessUserRecord.setBankName(pd.getString("bankName"));
			hhBusinessUserServiceImpl.updateUser(pd, businessUserRecord);
		}
		model.addAttribute("pd", pd);
		return getSuccessPd();
	}
	/**
	 * 提现
	 * @param request
	 * @param food
	 * @param model
	 * @return
	 */
	@RequestMapping("withdraw") 
	@ResponseBody
	public PageData withdraw(HttpServletRequest request,HhFood food,Model model){
		PageData pd=PageData.getToPageData(request);
		HhBusinessUser businessUser=(HhBusinessUser) request.getAttribute("businessUser");
		 
		String code=pd.getString("code");
		
		String cacheCode=usercache.getLoginCodeCacheValue(businessUser.getPhone());
		if(StringUtils.isEmpty(cacheCode)||!code.equals(cacheCode)){
			return getErrorPd("验证码错误");
		}
		usercache.putLoginCodeCacheValue(businessUser.getPhone(), "");
		//商家提现   余额清0   手续费 （需要不需要付）
		if(businessUser.getRole().equals(Constant.boss)){
			int result=hhBusinessServiceImpl.updateBusinessWithdraw(businessUser);
			if(result==0){
				return getErrorPd("操作失败");
			}
		}else{
		//员工
			int result=hhBusinessUserServiceImpl.updateBusinessWithdraw(businessUser);
			if(result==0){
				return getErrorPd("操作失败");
			}
		}
		return getSuccessPd();
	}
	
	
	
	/**
	 * 发送手机验证码
	 */
	@RequestMapping("sendCode")
	@ResponseBody
	public PageData sendCode(HttpServletRequest request,Model model){
		PageData pd=PageData.getPageDataByPage(request);
		 //发短信
        SendSmsResponse response;
		try {
			String code=String.valueOf((int)((Math.random()*9+1)*100000));
			//String code="1234";
			String phone=pd.getString("phone");
			
			HhBusinessUser businessUser=(HhBusinessUser) request.getAttribute("businessUser");
			if(businessUser!=null){
				phone=businessUser.getPhone();
				if(!StrUtil.isChinaPhoneLegal(phone)){
					return getErrorPd("手机号码格式不对,请修改个人信息");
				}
			} 
			
			HhBusinessUser user=hhBusinessUserServiceImpl.selectByPhone(phone);
			
			if(user==null){
				return getErrorPd("用户不存在");
			}
			response = SmsUtil.sendLoginCode(phone,code);
			if(response.getCode().equals("OK")){
				usercache.putLoginCodeCacheValue(phone, code);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		PageData successPd=getSuccessPd();
		return  successPd;
	}
}
